package cn.com.jdyun.service.impl;

import cn.com.jdyun.exception.BdexGatewayException;
import cn.com.jdyun.mapper.LotteryMapper;
import cn.com.jdyun.mapper.RewardPointsMapper;
import cn.com.jdyun.mapper.ext.ExtSysConfigMapper;
import cn.com.jdyun.pojo.Lottery;
import cn.com.jdyun.pojo.RewardPoints;
import cn.com.jdyun.pojo.SysConfig;
import cn.com.jdyun.pojo.UserWallet;
import cn.com.jdyun.service.LotteryService;
import cn.com.jdyun.service.UserWalletService;
import cn.com.jdyun.util.Constant;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

@Service
public class LotteryServiceImpl implements LotteryService {

    @Autowired
    private LotteryMapper lotteryMapper;
    @Autowired
    private RewardPointsMapper rewardPointsMapper;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private ExtSysConfigMapper sysConfigMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updatePoint(String userId, String amount, String coinType) throws BdexGatewayException {
        BigDecimal bAmount = new BigDecimal(amount);
        SysConfig lotteryLimitConfig = sysConfigMapper.selectByCode(Constant.LOTTERY_LIMIT);
        SysConfig texLotteryLimitConfig = sysConfigMapper.selectByCode(Constant.TEX_LOTTERY_LIMIT);
        //判断数额大于0
        if (bAmount.compareTo(BigDecimal.valueOf(0)) <= 0) {
            throw new BdexGatewayException("传入数值有误!");
        }
        Date cur = new Date();

        RewardPoints rewardPoints = rewardPointsMapper.queryUserRewardPoints(userId, coinType);
        if (rewardPoints == null) {
            rewardPoints = new RewardPoints();
            rewardPoints.setCoinAmount(amount);
            rewardPoints.setCoinType(coinType);
            rewardPoints.setUserId(userId);
            rewardPoints.setLeavesAmount(amount);
            rewardPoints.setTimes(0);
            rewardPoints.setCreateTime(cur);
            rewardPoints.setUpdateTime(cur);
            //获得抽奖次数
            int leaves = 0;
            if(Constant.COINTYPE_SSSP.equals(coinType)){
                leaves = bAmount.divide(new BigDecimal(lotteryLimitConfig.getInitValue()), 0, RoundingMode.DOWN).intValue();
            }else if(Constant.COINTYPE_TEX.equals(coinType)){
                leaves = bAmount.divide(new BigDecimal(texLotteryLimitConfig.getInitValue()), 0, RoundingMode.DOWN).intValue();
            }else{
                throw new BdexGatewayException("代币种类错误!");
            }
            rewardPoints.setLeaves(leaves);
            //保存充值记录
            int result1 = rewardPointsMapper.insert(rewardPoints);
            if (result1 <= 0) {
                throw new BdexGatewayException("插入充值记录失败!");
            }
        } else {
            BigDecimal coinAmount = new BigDecimal(rewardPoints.getCoinAmount());
            coinAmount = coinAmount.add(bAmount);
            rewardPoints.setCoinAmount(coinAmount.toString());
            BigDecimal leavesAmount = new BigDecimal(rewardPoints.getLeavesAmount());
            leavesAmount = leavesAmount.add(bAmount);
            rewardPoints.setLeavesAmount(leavesAmount.toString());
            //获得抽奖次数
            int leaves = 0;
            if(Constant.COINTYPE_SSSP.equals(coinType)){
                leaves =leavesAmount.divide(new BigDecimal(lotteryLimitConfig.getInitValue()), 0, RoundingMode.DOWN).intValue();
            }else if(Constant.COINTYPE_TEX.equals(coinType)){
                leaves = leavesAmount.divide(new BigDecimal(texLotteryLimitConfig.getInitValue()), 0, RoundingMode.DOWN).intValue();
            }else{
                throw new BdexGatewayException("代币种类错误!");
            }
            rewardPoints.setLeaves(leaves);
            rewardPoints.setUpdateTime(cur);
            int result2 = rewardPointsMapper.updateByPrimaryKeySelective(rewardPoints);
            if (result2 <= 0) {
                throw new BdexGatewayException("更新充值记录失败!");
            }
        }
    }

    @Transactional(readOnly = true)
    @Override
    public RewardPoints queryUserRewardPoints(String userId, String coinType) throws BdexGatewayException {
        return rewardPointsMapper.queryUserRewardPoints(userId, coinType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Lottery userLottery(String userId, String coinType) throws BdexGatewayException {
        SysConfig lotteryLimitConfig = sysConfigMapper.selectByCode(Constant.LOTTERY_LIMIT);
        RewardPoints rewardPoints = rewardPointsMapper.queryUserRewardPoints(userId, coinType);
        if (rewardPoints == null || rewardPoints.getLeaves() <= 0) {
            return null;
        }
        if (!rewardPoints.getCoinType().equals(Constant.COINTYPE_SSSP)) {
            return null;
        }
        //未参与抽奖的余额大于限额，才能获取一次抽奖机会
        if (new BigDecimal(rewardPoints.getLeavesAmount()).subtract(new BigDecimal(lotteryLimitConfig.getInitValue())).doubleValue() < 0) {
            return null;
        }
        Date cur = new Date();
        rewardPoints.setLeavesAmount(new BigDecimal(rewardPoints.getLeavesAmount()).subtract(new BigDecimal(lotteryLimitConfig.getInitValue())).toString());
        rewardPoints.setTimes(rewardPoints.getTimes() + 1);
        rewardPoints.setLeaves(rewardPoints.getLeaves() - 1);
        rewardPoints.setUpdateTime(cur);
        rewardPointsMapper.updateByPrimaryKeySelective(rewardPoints);
		/*//判断是否已经参与了抽奖
		Lottery lottery = lotteryMapper.selectByUserIdAndRechargeId(userId, rewardPoints.getId());
		if(lottery != null) {
			return lottery;
		}*/
        //计算获奖比例和获奖金额
        double random = Math.random();
        String rate = null;
        String[] array = null;
        for (String str : Constant.LOTTERY_CONFIG) {
            array = str.split(":");
            random = random - Double.valueOf(array[1]) / 100.0;
            if (random <= 0) {
                rate = array[0];
                break;
            }
        }
        String coinAmount = new BigDecimal(rewardPoints.getCoinAmount()).multiply(new BigDecimal(rate)).divide(new BigDecimal("100")).toString();
        //保存抽奖记录
        Lottery lottery = new Lottery();
        lottery.setCoinType(Constant.COINTYPE_SSSP);
        lottery.setRechargeId(rewardPoints.getId());
        lottery.setUserId(userId);
        lottery.setCreateTime(cur);
        lottery.setCoinAmount(coinAmount);
        lottery.setRate(rate);
        lotteryMapper.insert(lottery);
        //修改用户的钱包
        UserWallet wallet = userWalletService.queryByUserIdAndConiType(userId, Constant.COINTYPE_SSSP);
        BigDecimal freezeCoin = new BigDecimal(wallet.getFreezeCoin()).add(new BigDecimal(coinAmount));
        wallet.setFreezeCoin(freezeCoin.toString());
        userWalletService.updateWallet(wallet);

        return lottery;
    }

    @Transactional(readOnly = true)
    @Override
    public Page<Lottery> pageData(String userId, String coinType) throws BdexGatewayException {
        return lotteryMapper.pageData(userId, coinType);
    }

}
